#include "msg_queue.h"
#include <assert.h>
#include <string.h>

#include "led.h"



void CreateMessageQueue(MsgQueue* pQueue, Msg* array, uint16_t arraySize)
{
//	assert(pQueue && array && arraySize);
	
	memset(pQueue, 0, sizeof(MsgQueue));
	
	pQueue->msgArray  = array;
	pQueue->msgArraySize  = arraySize;
}



bool PostMessage(MsgQueue* pMsgQueue, uint16_t type, uint16_t id, uint32_t val, uint32_t param)
{	
	uint16_t inCursor  = pMsgQueue->inCursor;
	
//	assert(pMsgQueue);
	

	if(pMsgQueue->msgCounter < pMsgQueue->msgArraySize)
	{
		LED_On(LED1);
		pMsgQueue->msgArray[inCursor].type  = type;
		pMsgQueue->msgArray[inCursor].id    = id;
		pMsgQueue->msgArray[inCursor].value = val;
		pMsgQueue->msgArray[inCursor].param = param;
		
		pMsgQueue->inCursor++;
		
		if(pMsgQueue->inCursor >= pMsgQueue->msgArraySize)
		{
			pMsgQueue->inCursor  = 0;
		}
		
		pMsgQueue->msgCounter++;
		
		LED_Off(LED1);
		return true;
	}

	return false;
}



bool PeekMessage(MsgQueue* pMsgQueue, Msg* pMsg)
{
//	assert(pMsgQueue && pMsg);
	
	if(pMsgQueue->msgCounter > 0)
	{
		LED_On(LED2);
		memcpy(pMsg, &(pMsgQueue->msgArray[pMsgQueue->outCursor]), sizeof(Msg));
		
		pMsgQueue->outCursor++;
		if(pMsgQueue->outCursor >= pMsgQueue->msgArraySize)
		{
			pMsgQueue->outCursor  = 0;
		}
		
		pMsgQueue->msgCounter--;
		LED_Off(LED2);
		return true;
	}
	
	return false;
}

